package cd.zhixuan.utils;


/**
 * @author: HuZC
 * @Description:
 * @Date: 2022/1/10
 */
public class ObjectTools {

    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

    /**
     * 找到数据中指定的头或尾
     *
     * @param data     数据
     * @param find     要找的数据
     * @param findHead true：find数据作为报头，false：报尾
     * @return 0:返回数据；1:判断是否找到，null:未找到,byte[0]:找到了
     */
    public static byte[] findHeadTail(byte[] data, byte[] find, boolean findHead) {
        if (data == null || data.length == 0) {
            return null;
        }
        if (find == null || find.length == 0) {
            return null;
        }
        int dIndex = 0;
        int tempIndex;
        byte d, f;//数据
        Boolean findout = false;//
        while (dIndex < data.length) {
            for (int fIndex = 0; fIndex < find.length; fIndex++) {
                tempIndex = dIndex + fIndex;
                if (tempIndex >= data.length) {
                    findout = null;//表示未找到，之后的也不找了(长度不够了)
                    break;
                }

                d = data[tempIndex];
                f = find[fIndex];
                if (d == f) {
                    if (fIndex == find.length - 1) {
                        findout = true;//直到最后一位也相等
                        break;
                    }
                } else {
                    findout = false;
                    break;
                }
            }
            if (findout == null || findout) {
                break;
            }
            dIndex++;
        }

        if (findout == null || !findout) {
            return null;
        }

        int start, length;
        if (findHead) {
            start = dIndex;
            length = data.length - start;
            if (length <= 0) {
                return null;
            }
        } else {
            start = 0;
            length = dIndex + find.length;
            if (length > data.length) {
                length = data.length;
            }
        }

        byte[] res = new byte[length];

        System.arraycopy(data, start, res, 0, length);
        return res;
    }
}
